package com.sxbbc.agent.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.sxbbc.agent.common.CashMapping;
import com.sxbbc.agent.util.AgentSession;
import com.sxbbc.common.basics.files.qiniu.StringUtils;
import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.basics.rest.RestResponse;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.CashTypeEnums;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.impl.SysCashDetailsServiceImpl;
import com.sxbbc.common.core.utils.BasePage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@Controller
public class CashController {

    @Autowired
    private ISysCashDetailsService iSysCashDetailsService;
    @Autowired
    private IAgAccountService iAgAccountService;
    @Autowired
    private IBankDetailService iBankDetailService;
    @Autowired
    private ISysCashRuleService iSysCashRuleService;
    @Autowired
    private SysCashDetailsServiceImpl sysCashDetailsService;
    @Autowired
    private IBankDetailService bankDetailService;
    @Autowired
    private IBankTypeService iBankTypeService;
    @Autowired
    private IInfoParamService iInfoParamService;
    @Autowired
    private IAgAccountService agAccountService;
    @Autowired
    private IAccountChangeService iAccountChangeService;

    /**
     * 页面-提现申请记录
     * @return
     */
    @RequestMapping(value = CashMapping.SHOW_CASH)
    @ResponseBody
    private ModelAndView showCash(HttpServletRequest request){
        ModelAndView view=new ModelAndView(CashMapping.SHOW_CASH);
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return view;
        }
        AgAccount agAccount = iAgAccountService.selectByAgid(agent.getId());
        if(agAccount!=null){
            view.addObject("summoney",agAccount.getMoney());
        }
        return view;
    }
    
    /**
     * 页面-提现申请
     * @return
     */
    @RequestMapping(value = CashMapping.SHOW_CASH_APPLY)
    @ResponseBody
    private ModelAndView showCashApply(HttpServletRequest request){
        ModelAndView view=new ModelAndView(CashMapping.SHOW_CASH_APPLY);
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return  view;
        }
        //查询余额
        AgAccount agAccount = iAgAccountService.selectByAgid(agent.getId());
        if(agAccount!=null){
            view.addObject("summoney",agAccount.getMoney());
        }
        //查询银行卡
        BankDetail bank=new BankDetail();
        bank.setTargetId(agent.getId());

        List<BankDetail> bankList = iBankDetailService.queryBankDetailList(agent.getId(),CashTypeEnums.AGENT.getId());
        bankList.forEach(x -> x.setLastCode(x.getBankCard().substring(x.getBankCard().length()-4,x.getBankCard().length())));
        CalcuUtils calcuUtils=new CalcuUtils();
        //查询提现规则
        QueryWrapper<SysCashRule> wrapper=new QueryWrapper<>();
        wrapper.eq("role_type",CashTypeEnums.AGENT.getId());
        SysCashRule sysCashRule = iSysCashRuleService.getOne(wrapper);
        view.addObject("bankList",bankList);
        view.addObject("rule",sysCashRule);
        view.addObject("scale",calcuUtils.mul(sysCashRule.getScale(), BigDecimal.valueOf(100),2).stripTrailingZeros().toBigInteger());
        return view;
    }
    
    /**
     * 申请提现
     * @param cash
     * @return
     */
    @RequestMapping(value = CashMapping.HANDLE_CASH_APPLY)
    @ResponseBody
    public com.function.common.RestResponse cashApply(HttpServletRequest request, SysCashDetails cash){
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return GetRest.getFail("获取代理信息失败");
        }
        cash.setTargetId(agent.getId());
        cash.setType(CashTypeEnums.AGENT.getId());
        //判断是否符合提现规则
        com.function.common.RestResponse restResponse = sysCashDetailsService.handleCashApply(cash);
        return restResponse;
    }
    

    /**
     *数据接口-提现申请记录
     * @return
     */
    @RequestMapping(value = CashMapping.QUERY_CASH_DETAIL)
    @ResponseBody
    private RestResponse queryCash(HttpServletRequest request, BasePage<SysCashDetails> page,SysCashDetails sysCashDetails){
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return RestFactory.fail("获取代理信息失败");
        }
        QueryWrapper<SysCashDetails> wrapper=new QueryWrapper<>();
        wrapper.eq("target_id",agent.getId());
        wrapper.eq("type", CashTypeEnums.AGENT.getId());
        if(!StringUtils.isNullOrEmpty(sysCashDetails.getPayCode())){
            wrapper.eq("pay_code",sysCashDetails.getPayCode());
        }
        if(sysCashDetails.getStatus()!=null){
            wrapper.eq("status",sysCashDetails.getStatus());
        }
        if(!StringUtils.isNullOrEmpty(sysCashDetails.getBankName())){
            wrapper.like("bank_name",sysCashDetails.getBankName());
        }
        if(!StringUtils.isNullOrEmpty(sysCashDetails.getTimestr())){
            String[] timeArr = sysCashDetails.getTimestr().split("~");
            if(!StringUtils.isNullOrEmpty(timeArr[0]) && !StringUtils.isNullOrEmpty(timeArr[1])){
                wrapper.between("create_time",timeArr[0],timeArr[1]);
            }
        }
        wrapper.orderByDesc("create_time");
        iSysCashDetailsService.page(page,wrapper);

        return RestFactory.success(page.getRecords(),page.getTotal());
    }


    /**
     * 页面-银行卡列表
     * @return
     */
    @RequestMapping(value = CashMapping.SHOW_BANK_DETAIL)
    public ModelAndView showBankDetail(){
        ModelAndView view=new ModelAndView(CashMapping.SHOW_BANK_DETAIL);
        return view;
    }

    /**
     *数据接口-银行卡列表
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = CashMapping.QUERY_BANK_DETAIL)
    @ResponseBody
    public RestResponse queryBankDetail(HttpServletRequest request, BasePage<BankDetail> page){
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return RestFactory.fail("获取代理信息失败");
        }
        QueryWrapper<BankDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("target_id", agent.getId());
        wrapper.eq("type", CashTypeEnums.AGENT.getId());

        bankDetailService.page(page,wrapper);
        List<BankDetail> records = page.getRecords();
        //查询银行卡对应的银行
        for (BankDetail b :records) {
            BankType bankType = iBankTypeService.getById(b.getTypeId());
            b.setBankName(bankType.getBankName());
        }
        return RestFactory.success(page.getRecords(),page.getTotal());
    }

    /**
     *数据接口-银行卡列表
     * @return
     */
    @RequestMapping(value = CashMapping.SHOW_ADD_BANK)
    @ResponseBody
    public ModelAndView showaddbank(BasePage<BankType> page,Integer bankId){
        ModelAndView view=new ModelAndView(CashMapping.SHOW_ADD_BANK);
        QueryWrapper<BankType> wrapper=new QueryWrapper<>();
        iBankTypeService.page(page, wrapper);
        view.addObject("banktype",page.getRecords());
        //id不为空-修改编辑
        if(bankId!=null){
            BankDetail bankDetail = bankDetailService.getById(bankId);
            view.addObject("bank",bankDetail);
        }
        return  view;
    }


    /**
     * 添加银行卡
     * @param detail 银行卡对象
     * @return 处理结果
     */
    @RequestMapping(value = CashMapping.ADD_BANK)
    @ResponseBody
    public com.function.common.RestResponse addBankDetail (HttpServletRequest request, BankDetail detail) {
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return GetRest.getFail("获取代理信息失败");
        }
        detail.setTargetId(agent.getId());
        detail.setType(CashTypeEnums.AGENT.getId());
        com.function.common.RestResponse result = bankDetailService.editBankDetail(detail);
        return result;
    }

    /**
     *删除银行卡
     * @return
     */
    @RequestMapping(value=CashMapping.DELETE_BANK_BYID)
    @ResponseBody
    public com.function.common.RestResponse deleteBankById(HttpServletRequest request,Integer bankId){
        AgAgent agent = AgentSession.getAgent(request);
        if (agent == null) {
            return GetRest.getFail("获取代理信息失败");
        }
        BankDetail bank = bankDetailService.getById(bankId);
        if(bank!=null && bank.getType().equals(CashTypeEnums.AGENT.getId())){
            bankDetailService.removeById(bankId);
            return GetRest.getSuccess("操作成功");
        }
        return GetRest.getFail("操作失败，请检查数据是否正常");
    }
}
